import os
import _pickle as cPickle
import numpy as np
from scipy.io.wavfile import read
from speakerfeatures import extract_features
import warnings
warnings.filterwarnings("ignore")
import time
import datetime
starttime = datetime.datetime.now()

modelpath = "bear_models/"
file_paths = "test"

gmm_files = [os.path.join(modelpath,fname) for fname in
              os.listdir(modelpath) if fname.endswith('.gmm')]

#Load the Gaussian gender Models
models    = [cPickle.load(open(fname,'rb')) for fname in gmm_files]
speakers   = [fname.split("\\")[-1].split(".gmm")[0].split("/")[1] for fname
              in gmm_files]

print(speakers)

#softmax
def softmax(x):
    return np.exp(x)/np.sum(np.exp(x),axis=0)

# Read the test directory and get the list of test audio files
fect_true = 0
fect_false = 0
pre_0_true = 0
pre_peo_true = 0
pre_peo_all = 0
for wav in os.listdir(file_paths):
    sr,audio = read(os.path.join(file_paths,wav))
    vector   = extract_features(audio,sr)
    #print(vector)
    log_likelihood = np.zeros(len(models))
    #print(log_likelihood)
    for i in range(len(models)):
        gmm    = models[i]         #checking with each model one by one
        scores = np.array(gmm.score(vector))
        log_likelihood[i] = scores.sum()
    winner = np.argmax(log_likelihood)
    if max(softmax(log_likelihood)) > 0.8: pre_speaker = speakers[winner]
    else : pre_speaker = 'Nobody'
    print(max(softmax(log_likelihood)))
    print(wav ,"\tdetected as - ", pre_speaker)